import { Button, message, Space, Step, Steps } from 'ant-design-vue'
import { omit } from 'lodash-es'
import moment from 'moment'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { commonApi, unpackApi } from '@/apis'
import { GetCouponListTypeRes } from '@/apis/commonTypes'
import { useBack } from '@/hooks'
import { AwardSettingItem, FROM_DATA } from '@/views/marketing/unpack/types'

import AwardForm from './awardForm'
import BaseForm from './baseForm'
import ConditionForm from './conditionForm'
import styles from './index.module.css'
import TipsForm from './tipsForm'
export default defineComponent({
  name: 'UnpackForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const current = ref(0)
    const formData = ref({
      /** 活动名称 */
      activityName: '',
      /** 活动周期 */
      date: [],
      /** 活动模板 */
      activityTemplate: '',
      /** 全面屏手机活动背景 */
      activityMobileBackground: '',
      /** 活动首页宣传图 */
      activityIndexBanner: '',
      /** 按钮文字 */
      buttonWord: '#000000',
      /** 按钮背景 */
      buttonBackground: '#000000',
      /** 活动详情 */
      activityInfo: '',
      activityRule: {
        /** 开箱基础次数 */
        openTimes: '',
        openTimesType: 0,
        /** 最大中将次数 */
        maxTimes: '',
        /** 最大中间次数单选框 */
        maxTimesType: 0,
        /** 默认奖项内容 */
        defaultPrizeInfo: '',
        /** 默认奖项类型
         * - `0`空
         * - `1`积分
         * - `2`开箱次数
         * - `3`卡卷
         */
        defaultPrizeType: 0,
        /** 浏览小程序秒数 */
        browseSeconds: '',
        /** 浏览小程序赠送开箱次数 */
        browseGiveNum: '',
        /** 浏览小程序赠送上限次数	 */
        browseLimitNum: '',
        /** 浏览小程序单选框 */
        browseType: 0,
        /** 多选框信息 */
        checkboxes: [],
        /** 邀请好友数量 */
        invitationTimes: '',
        /** 邀请好友赠送开箱次数	 */
        invitationGiveNum: '',
        /** 邀请好友赠送上限次数	 */
        invitationLimitNum: '',
        /** 邀请好友单选框	 */
        invitationType: 0,
        /** 观看视频赠送开箱次数 */
        watchGiveNum: '',
        /** 观看视频赠送上限次数	 */
        watchLimitNum: '',
        /** 观看视频秒数	 */
        watchSeconds: '',
        /** 观看视频单选框	 */
        watchType: 0,
        /** 分享视频赠送开箱次数*/
        shareGiveNum: '',
        /** 分享视频赠送上限次数	 */
        shareLimitNum: '',
        /** 分享视频单选框	 */
        shareType: 0,
        /** 完善个人信息赠送开箱次数*/
        perfectInformationGiveNum: '',
        /** 累计开箱次数 */
        cumulativeOpenNum: '',
        /** 累计开箱单选框	 */
        cumulativeOpenType: 0,
        /** 累计开箱赠送类型单选框
         * - `0`积分
         * - `1`开箱次数
         * - `2`卡券
         */
        cumulativeOpenGiveType: '',
        /** 累计开箱赠送内容	 */
        cumulativeOpenGiveInfo: ''
      },
      prizeList: [
        {
          /** 奖项名称 */
          prizeName: '',
          /** 奖项类型
           * - `0`积分
           * - `1`开箱次数
           * - `2`卡券
           */
          prizeType: '',
          /** 奖项内容 */
          prizeInfo: '',
          /** 二维码图 */
          qrCodeUrl: '',
          /** 奖项图片 */
          prizePicture: '',
          /** 中奖概率 */
          winningProbability: '',
          /** 库存 */
          prizeStock: ''
        }
      ],
      /** 不符合条件提示 */
      unqualifiedTips: '您的条件不符合当前抽奖活动！',
      /** 活动已结束提示 */
      activityEndedTips: '该活动已经结束！！',
      /** 活动未开始提示 */
      activityNotStartedTips: '活动尚未开始，敬请期待！',
      /** 积分不足提示 */
      pointNotEnoughTips: '积分不足！',
      /** 中奖时提示 */
      winningTips: '恭喜您，中奖啦！',
      /** 未中奖提示 */
      losingTips: '不好意思，您没中奖！'
    } as FROM_DATA)
    const baseForm = ref<ComponentRef>({})
    const tipsForm = ref<ComponentRef>({})
    const awardForm = ref<ComponentRef>({})
    const conditionForm = ref<ComponentRef>({})
    const route = useRoute()
    const steps = [
      {
        title: '基本信息'
      },
      {
        title: '奖励设置'
      },
      {
        title: '参与条件'
      },
      {
        title: '提示内容'
      }
    ]
    const couponListOption = ref([] as GetCouponListTypeRes)
    const { handleCancel } = useBack('refreshUnpackList')
    function handleNext() {
      const map = {
        0: baseForm,
        1: awardForm,
        2: conditionForm
      }
      map[current.value]
        .value!.submit()
        .then(() => {
          current.value++
        })
        .catch(e => {
          message.error(e || '请输入页面提示内容')
        })
    }
    function handlePrevious() {
      current.value--
    }
    function handleSave() {
      tipsForm.value!.submit().then(() => {
        console.log('提示内容完成')
        const data = {
          ...omit(formData.value, ['date']),
          startTime: formData.value.date[0].format('x'),
          endTime: formData.value.date[1].format('x')
        }
        if (props.isEdit) {
          unpackApi.editUnpack(data).then(() => {
            message.success('编辑翻牌')
            handleCancel()
          })
        } else {
          unpackApi.createUnpack(data).then(() => {
            message.success('创建成功')
            handleCancel()
          })
        }
      })
    }
    function addSettting(val: AwardSettingItem) {
      formData.value.prizeList.push(val)
    }
    function handleAwardUpload(val) {
      formData.value.prizeList[val.key].prizePicture = val.url
    }
    function handleBaseUpload(val) {
      formData.value[val.name] = val.url
    }
    function handleRadioChange(val) {
      console.log(val)
      formData.value.prizeList[val].prizeInfo = ''
    }
    function handleConCumRadioChange() {
      formData.value.activityRule.cumulativeOpenGiveInfo = ''
    }
    function handleConDeaRadioChange() {
      formData.value.activityRule.defaultPrizeInfo = ''
    }
    function deletePrizeList(index) {
      formData.value.prizeList.splice(index, 1)
    }

    function init() {
      commonApi.getCouponTypeList({ type: '3' }).then(res => {
        couponListOption.value = res
      })
      if (props.isEdit) {
        const id = route.query.id
        unpackApi.getUnpackDetail({ id }).then(res => {
          if (res.activityRule.defaultPrizeType === 3) {
            if (
              couponListOption.value.findIndex(
                v => v.id == res.activityRule.defaultPrizeInfo
              ) === -1
            ) {
              res.activityRule.defaultPrizeInfo = ''
            }
          }
          res.prizeList.forEach(item => {
            if (item.prizeType === 3) {
              if (
                couponListOption.value.findIndex(
                  v => v.id == item.prizeInfo
                ) === -1
              ) {
                item.prizeInfo = ''
              }
            }
          })
          formData.value = Object.assign(formData.value, {
            ...omit(res, ['endTime', 'startTime']),
            date: [moment(res.startTime, 'x'), moment(res.endTime, 'x')]
          })
        })
      }
    }
    onMounted(() => {
      init()
    })
    return {
      current,
      formData,
      baseForm,
      tipsForm,
      awardForm,
      conditionForm,
      steps,
      couponListOption,
      handleNext,
      handlePrevious,
      handleSave,
      handleCancel,
      addSettting,
      handleAwardUpload,
      handleRadioChange,
      handleBaseUpload,
      handleConCumRadioChange,
      handleConDeaRadioChange,
      deletePrizeList
    }
  },
  render() {
    const stepMapItem = item => <Step title={item.title} />
    const fromMap = {
      0: (
        <BaseForm
          ref="baseForm"
          formData={this.formData}
          onHandleBaseUpload={this.handleBaseUpload}
        />
      ),
      1: (
        <AwardForm
          ref="awardForm"
          formData={this.formData}
          couponListOption={this.couponListOption}
          onAddSettting={this.addSettting}
          onHandleAwardUpload={this.handleAwardUpload}
          onHandleRadioChange={this.handleRadioChange}
          onDeletePrizeList={this.deletePrizeList}
        />
      ),
      2: (
        <ConditionForm
          ref="conditionForm"
          formData={this.formData.activityRule}
          couponListOption={this.couponListOption}
          onHandleConCumRadioChange={this.handleConCumRadioChange}
          onHandleConDeaRadioChange={this.handleConDeaRadioChange}
        />
      ),
      3: <TipsForm ref="tipsForm" formData={this.formData} />
    }
    return (
      <div class={styles.wrap}>
        <Steps current={this.current}>{this.steps.map(stepMapItem)}</Steps>
        <div>{fromMap[this.current]}</div>
        <div class={styles.footer}>
          <Space>
            <Button type="primary" onClick={this.handleCancel}>
              返回列表
            </Button>
            {this.current > 0 ? (
              <Button type="primary" onClick={this.handlePrevious}>
                上一步
              </Button>
            ) : null}
            {this.current < 3 ? (
              <Button type="primary" onClick={this.handleNext}>
                下一步
              </Button>
            ) : null}
            {this.current === 3 ? (
              <Button type="primary" onClick={this.handleSave}>
                保存
              </Button>
            ) : null}
          </Space>
        </div>
      </div>
    )
  }
})
